import 'package:flutter/material.dart';
import 'package:flutter_mall_app/common/navifator_push.dart';
import 'package:flutter_mall_app/pages/details_product/details_product_page.dart';
import 'package:flutter_page_indicator/flutter_page_indicator.dart';
import 'package:flutter_spinkit/flutter_spinkit.dart';
import 'dart:convert';
import '../api/api_methods.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:url_launcher/url_launcher.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:common_utils/common_utils.dart';

///商城首页
class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage>
    with SingleTickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  var _futureBuilderFuture;

  @override
  // TODO: implement wantKeepAlive
  bool get wantKeepAlive => true;
  var formData = {'lon': '115.02932', 'lat': '35.76189'};
  int page = 1;
  List<Map> hotGoodsList = [];
  GlobalKey<RefreshFooterState> _footerKey = new GlobalKey<RefreshFooterState>();
  GlobalKey<RefreshHeaderState> _headererKey = new GlobalKey<RefreshHeaderState>();

  @override
  void initState() {
    super.initState();
    debugPrint("首页数据开始加载。。。");
    //使用成员变量保存future防止FutureBuilder的多次重绘
    _futureBuilderFuture = request("homePageContent", formData: formData);
  }

  @override
  Widget build(BuildContext context) {
    debugPrint("数据加载或刷新。。。");
    return Scaffold(
      appBar: AppBar(
        title: Text("商城首页"),
      ),
      body: FutureBuilder(
        future: _futureBuilderFuture,
        builder: (BuildContext context, AsyncSnapshot snapshot) {
          if (snapshot.hasData) {
            var data = json.decode(snapshot.data.toString());
            List<Map> swiper = (data['data']['slides'] as List).cast();
            List<Map> gridViewList = (data['data']['category'] as List).cast();
            String url = data['data']['advertesPicture']['PICTURE_ADDRESS'];
            String leaderImage = data['data']['shopInfo']['leaderImage'];
            String leaderPhone = data['data']['shopInfo']['leaderPhone'];
            List<Map> recommendList = (data['data']['recommend'] as List).cast();
            String floor1Title = data['data']['floor1Pic']['PICTURE_ADDRESS']; //楼层1的标题图片
            List<Map> floor1 = (data['data']['floor1'] as List).cast(); //楼层1商品和图片
            String floor2Title = data['data']['floor2Pic']['PICTURE_ADDRESS']; //楼层1的标题图片
            List<Map> floor2 = (data['data']['floor2'] as List).cast(); //楼层1商品和图片
            String floor3Title = data['data']['floor3Pic']['PICTURE_ADDRESS']; //楼层1的标题图片
            List<Map> floor3 = (data['data']['floor3'] as List).cast(); //楼层1商品和图片
            return EasyRefresh(
              child: ListView(
                children: <Widget>[
                  SwiperWidget(swiperDataList: swiper),
                  TopNavigator(girdViewList: gridViewList),
                  AdBanner(adUrl: url),
                  DialNumber(image: leaderImage, phone: leaderPhone),
                  RecommendList(recommendList: recommendList),
                  FloorTitle(imageUrl: floor1Title),
                  FloorProduct(floorProductLst: floor1),
                  FloorTitle(imageUrl: floor2Title),
                  FloorProduct(floorProductLst: floor2),
                  FloorTitle(imageUrl: floor3Title),
                  FloorProduct(floorProductLst: floor3),
                  _hotList(),
                ],
              ),
              onRefresh: ()async{
                await new Future.delayed(const Duration(seconds: 1), () {
                  setState(() {
                    _futureBuilderFuture = null;
                    _futureBuilderFuture =  request("homePageContent", formData: formData);
                  });
                });
              },
              refreshHeader: ClassicsHeader(
                key: _headererKey,
                bgColor: Colors.redAccent[100],
                textColor: Colors.black,
                moreInfoColor: Colors.black,
                refreshText: "下拉刷新",
                refreshReadyText: "松开刷新",
                refreshingText: "正在刷新...",
                refreshedText: "刷新完成",
              ),
              loadMore: () async {
                var formData = {'page': page};
                await request("homePageBelowContent", formData: formData).then((value) {
                  var data = json.decode(value.toString());
                  List<Map> newProductList = (data['data'] as List).cast();
                  setState(() {
                    hotGoodsList.addAll(newProductList);
                    page++;
                  });
                });
              },
              refreshFooter: ClassicsFooter(
                key: _footerKey,
                bgColor: Colors.redAccent[100],
                textColor: Colors.black,
                moreInfoColor: Colors.black,
                showMore: true,
                loadReadyText: '松开加载',
                loadText: "上拉加载",
                moreInfo:
                    '最后加载时间：${DateUtil.formatDateTime(DateTime.now().toString(), DateFormat.HOUR_MINUTE, "/", ":")}',
                loadingText: '正在加载...',
                loadedText: "加载完成",
                noMoreText: "",
              ),
            );
          } else {
            return Center(
              child: SpinKitFadingCircle(
                itemBuilder: (_, int index) {
                  return DecoratedBox(
                    decoration: BoxDecoration(
                      color: index.isEven ? Colors.red : Colors.green,
                    ),
                  );
                },
              ),
            );
          }
        },
      ),
    );
  }

  //火爆专区列表
  Widget _hotList() {
    return Container(
      child: Column(
        children: <Widget>[
          Container(
            child: Text("火爆专区"),
            margin: EdgeInsets.only(top: 10.0),
            padding: EdgeInsets.all(5.0),
            alignment: Alignment.center,
            decoration: BoxDecoration(
                color: Colors.white,
                border: Border(bottom: BorderSide(width: 0.5, color: Colors.black12))),
          ),
          _wrapList(),
        ],
      ),
    );
  }

  Widget _wrapList() {
    if (hotGoodsList.length != 0) {
      List wrapList = hotGoodsList.map((value) {
        return InkWell(
          child: Container(
            width: ScreenUtil().setWidth(372),
            color: Colors.white,
            padding: EdgeInsets.all(5.0),
            margin: EdgeInsets.only(bottom: 3.0),
            child: Column(
              children: <Widget>[
                Image.network(
                  value['image'],
                  width: ScreenUtil().setWidth(375),
                ),
                Text(
                  value['name'],
                  maxLines: 1,
                  overflow: TextOverflow.ellipsis,
                  style: TextStyle(color: Colors.pink, fontSize: ScreenUtil().setSp(26)),
                ),
                Row(
                  children: <Widget>[
                    Text('￥${value['mallPrice']}'),
                    SizedBox(width: 8.0),
                    Text(
                      '￥${value['price']}',
                      style:
                          TextStyle(color: Colors.black26, decoration: TextDecoration.lineThrough),
                    )
                  ],
                )
              ],
            ),
          ),
          onTap: () {
            NavigationPush.pushDetailsProduct(context,value['goodsId']);
          },
        );
      }).toList();
      return Wrap(
        spacing: 2,
        children: wrapList,
      );
    } else {
      return Text(' ');
    }
  }
}

///首页轮播
class SwiperWidget extends StatelessWidget {
  final List swiperDataList;

  const SwiperWidget({Key key, this.swiperDataList}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(300),
      width: double.infinity,
      child: Swiper(
        indicatorLayout: PageIndicatorLayout.SCALE,
        scale: 0.95,
        viewportFraction: 0.9,
        pagination: SwiperPagination(),
        autoplay: true,
        itemCount: swiperDataList.length,
        itemBuilder: (BuildContext context, int index) {
          return ClipRRect(
            child: InkWell(
              onTap: (){
                NavigationPush.pushDetailsProduct(context,swiperDataList[index]['goodsId']);
              },
              child: CachedNetworkImage(
                imageUrl: "${swiperDataList[index]['image']}",
                fit: BoxFit.cover,
                placeholder: (context, imageUrl) {
                  return Icon(Icons.broken_image, size: 50);
                },
              ),
            ),
            borderRadius: BorderRadius.circular(12.0),
          );
        },
      ),
    );
  }
}

///首页导航
class TopNavigator extends StatelessWidget {
  final List girdViewList;

  const TopNavigator({Key key, this.girdViewList}) : super(key: key);

  Widget _girdViewItem(BuildContext context, item) {
    return InkWell(
      child: Column(
        children: <Widget>[
          CachedNetworkImage(imageUrl: "${item['image']}", width: ScreenUtil().setWidth(95)),
          Text("${item['mallCategoryName']}"),
        ],
      ),
      onTap: () {},
    );
  }

  @override
  Widget build(BuildContext context) {
    if (girdViewList.length > 10) {
      girdViewList.removeRange(10, girdViewList.length);
    }
    return Container(
      height: ScreenUtil().setHeight(260),
      padding: EdgeInsets.all(3.0),
      child: GridView.count(
        physics: NeverScrollableScrollPhysics(),
        crossAxisCount: 5,
        padding: EdgeInsets.all(4.0),
        children: girdViewList.map((item) {
          return _girdViewItem(context, item);
        }).toList(),
      ),
    );
  }
}

///广告
class AdBanner extends StatelessWidget {
  final String adUrl;

  const AdBanner({Key key, this.adUrl}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(child: CachedNetworkImage(imageUrl: "$adUrl"));
  }
}

///拨打电话
class DialNumber extends StatelessWidget {
  final String image;
  final String phone;

  const DialNumber({Key key, this.image, this.phone}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: InkWell(
        child: CachedNetworkImage(imageUrl: "$image"),
        onTap: _launchUrl,
      ),
    );
  }

  void _launchUrl() async {
    String url = "tel:" + phone;
    if (await canLaunch(url)) {
      await launch(url);
    } else {
      throw Exception("拨打电话失败");
    }
  }
}

///商品推荐
class RecommendList extends StatelessWidget {
  final List recommendList;

  const RecommendList({Key key, this.recommendList}) : super(key: key);

  //标题
  Widget _title() {
    return Container(
      alignment: Alignment.centerLeft,
      padding: EdgeInsets.fromLTRB(10, 2, 0, 5),
      decoration: BoxDecoration(
        color: Colors.white,
        border: Border(
        ),
      ),
      child: Text("商品推荐", style: TextStyle(color: Colors.redAccent, fontWeight: FontWeight.bold)),
    );
  }

  //推荐商品Item
  Widget _productItem(context,index) {
    return InkWell(
      child: Container(
        width: ScreenUtil().setWidth(300),
        height: ScreenUtil().setHeight(250),
        padding: EdgeInsets.all(8),
        decoration: BoxDecoration(
            color: Colors.white,
            border: Border(
            )),
        child: Column(
          children: <Widget>[
            CachedNetworkImage(imageUrl: "${recommendList[index]['image']}"),
            Text("￥ ${recommendList[index]['mallPrice']}"),
            Text("￥ ${recommendList[index]['price']}",
                style: TextStyle(decoration: TextDecoration.lineThrough, color: Colors.grey)),
          ],
        ),
      ),
      onTap: () {
        NavigationPush.pushDetailsProduct(context,recommendList[index]['goodsId']);
      },
    );
  }

  //横向列表
  Widget _recommendList() {
    return Container(
      height: ScreenUtil().setHeight(320),
      child: ListView.builder(
        scrollDirection: Axis.horizontal,
        itemCount: recommendList.length,
        itemBuilder: (context, index) {
          return _productItem(context,index);
        },
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      height: ScreenUtil().setHeight(370),
      margin: EdgeInsets.only(top: 10),
      child: Column(
        children: <Widget>[
          _title(),
          _recommendList(),
        ],
      ),
    );
  }
}

///楼层标题
class FloorTitle extends StatelessWidget {
  final String imageUrl;

  const FloorTitle({Key key, this.imageUrl}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.all(8.0),
      child: CachedNetworkImage(imageUrl: imageUrl),
    );
  }
}

///楼层商品
class FloorProduct extends StatelessWidget {
  final List floorProductLst;

  const FloorProduct({Key key, this.floorProductLst}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        children: <Widget>[
          _product1(context),
          _otherItem(context),
        ],
      ),
    );
  }

  Widget _product1(context) {
    return Row(
      children: <Widget>[
        _productItem(context,floorProductLst[0]),
        Column(
          children: <Widget>[
            _productItem(context,floorProductLst[1]),
            _productItem(context,floorProductLst[2]),
          ],
        )
      ],
    );
  }

  Widget _otherItem(context) {
    return Row(
      children: <Widget>[
        _productItem(context,floorProductLst[3]),
        _productItem(context,floorProductLst[4]),
      ],
    );
  }

  Widget _productItem(context,Map item) {
    return Container(
      width: ScreenUtil().setWidth(375),
      child: InkWell(
        child: CachedNetworkImage(imageUrl: item['image']),
        onTap: () {
          NavigationPush.pushDetailsProduct(context,item['goodsId']);
        },
      ),
    );
  }

  void pushDetailsProduct(context,String id){
    Navigator.of(context).push(MaterialPageRoute(builder: (context){
      return DetailsProductPage(id: id);
    }));
  }
}
